package com.mf.ergate.web.security.captcha;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.Objects;

public class CaptchaAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

	private static final String SPRING_SECURITY_FORM_CAPTCHA_KEY = "captcha";
	private String captchaParameter;

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
		if(StringUtils.isEmpty(this.captchaParameter)){
			this.captchaParameter = SPRING_SECURITY_FORM_CAPTCHA_KEY;
		}
		String captchaInRequest = request.getParameter(captchaParameter) != null ? request.getParameter(captchaParameter) : "";
		String captchaInSession = CaptchaUtils.getCaptchaValue(request);
		if (!Objects.equals(captchaInSession, captchaInRequest)) {
			throw new AuthenticationServiceException("验证码输入错误");
		}
		return super.attemptAuthentication(request, response);
	}

	public void setCaptchaParameter(String captchaParameter){
		this.captchaParameter = captchaParameter;
	}
}
